import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-04-20
 * Time: 22:22
 */


public class Solution {
    public static int maxEvents(int[][] events) {
        Arrays.sort(events, (o1, o2) -> o1[0] - o2[0]);
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        int num = events.length;
        int count = 0;
        int i = 0;
        int curDay = 1;
        while (i < num || !minHeap.isEmpty()) {
            while (i < num && events[i][0] == curDay){
                // 将开始时间是同一天的事情放到小根堆里面
                minHeap.add(events[i][1]);
                i++;
            }
            // 删除那些已经结束的活动
            while (!minHeap.isEmpty() && minHeap.peek() < curDay){
                minHeap.poll();
            }
            // 选择开始时间相同的事件中, 结束时间最早的活动进行执行
            if(!minHeap.isEmpty()){
                minHeap.poll();
                count++;
            }
            // 开始下一轮
            curDay++;
        }
        return count;
    }
}
